import datetime
import os
import json
import re
from datetime import datetime
from loguru import logger


def _assess_task_complexity(self, command: str) -> tuple[str, bool]:
        """Assesses the complexity and urgency of a task using an LLM."""
        current_date = datetime.now().strftime("%Y年%m月%d日 %H:%M:%S")
        current_working_dir = os.getcwd()
        prompt = f"""Assess the complexity and urgency of the following user command.
Current Date and Time: {current_date}
Operating System: {self.os_info}
Current Working Directory: {current_working_dir}
User Command: "{command}"

Respond with a single JSON object with two keys:
- "complexity": "simple" or "complex"
- "urgency": true or false (true if the command implies urgency, e.g., using words like 'quickly', 'immediately', 'now', '马上', '立刻').

Example 1:
User Command: "list files in the current directory"
Response: {{\"complexity\": \"simple\", \"urgency\": false}}

Example 2:
User Command: "refactor the entire authentication module to use a new library"
Response: {{\"complexity\": \"complex\", \"urgency\": false}}

Example 3:
User Command: "马上给我总结一下这个文件"
Response: {{"complexity": "simple", "urgency": true}}
"""
        response_data = self.llm.generate_content(prompt, task_type="classification")
        response = response_data["output_content"]
        self.llm_usage_metrics["total_input_tokens"] += response_data["input_tokens"]
        self.llm_usage_metrics["total_output_tokens"] += response_data["output_tokens"]
        self.llm_usage_metrics["total_cost"] += response_data["cost"]
        self.llm_usage_metrics["task_llm_metrics"].append({
            "task_type": "classification",
            "input_tokens": response_data["input_tokens"],
            "output_tokens": response_data["output_tokens"],
            "cost": response_data["cost"]
        })

        try:
            # First, try to parse the response directly as JSON
            assessment = json.loads(response.strip())
            complexity = assessment.get("complexity", "complex")
            urgency = assessment.get("urgency", False)
            logger.info(f"Task complexity assessment for '{command}': Complexity={complexity}, Urgency={urgency})")
            return complexity, urgency
        except json.JSONDecodeError:
            # If direct parsing fails, try to extract JSON from markdown code block
            json_match = re.search(r'```json\n(.*?)```', response, re.DOTALL)
            if json_match:
                json_string = json_match.group(1).strip()
            else:
                # Try to find a JSON-like string even if not in a markdown block
                json_string_match = re.search(r'\{.*\}', response, re.DOTALL)
                if json_string_match:
                    json_string = json_string_match.group(0).strip()
                else:
                    logger.error(f"Error assessing task complexity: No valid JSON found in response. LLM Response: {response}. Defaulting to 'complex' and 'false'.")
                    return "complex", False
            try:
                assessment = json.loads(json_string)
                complexity = assessment.get("complexity", "complex")
                urgency = assessment.get("urgency", False)
                logger.info(f"Task complexity assessment for '{command}': Complexity={complexity}, Urgency={urgency})")
                return complexity, urgency
            except json.JSONDecodeError as e:
                logger.error(f"Error assessing task complexity: Failed to parse JSON. Error: {e}. LLM Response: {response}. Defaulting to 'complex' and 'false'.")
                return "complex", False
        except KeyError as e:
            logger.error(f"Error assessing task complexity: Missing key in JSON response. Error: {e}. LLM Response: {response}. Defaulting to 'complex' and 'false'.")
            return "complex", False
        except Exception as e:
            logger.error(f"An unexpected error occurred during task complexity assessment: {e}. LLM Response: {response}. Defaulting to 'complex' and 'false'.")
            return "complex", False
